﻿using System;
using MySql.Simple.Mapper.Attributes;

namespace MySql.Simple.Mapper.Finders
{
    /// <summary>
    /// Finds the SQL table name to store a classes data in.
    /// </summary>
    public static class TableNameFinder
    {
        /// <summary>
        /// Finds the SQL table name for the specified target.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        public static string Find(Type target)
        {
            var tableName = string.Empty;

            target = target.GetInnerElementType();

            var attributes = target.GetCustomAttributes(typeof(TableAttribute), false);

            foreach (var attribute in attributes)
            {
                var tableAttribute = (TableAttribute)attribute;

                tableName = tableAttribute.Name;

                if (!string.IsNullOrEmpty(tableName)) continue;

                // Make Plural
                tableName = Inflector.Pluralize(target.Name);

                // Convert to underscored
                tableName = Inflector.Underscore(tableName);
            }

            return tableName;
        }
    }
}